import sqlite3
import os
import sys
from pathlib import Path
from datetime import datetime

# 修复Windows路径问题：使用绝对路径
BASE_DIR = Path(__file__).resolve().parent.parent
DB_PATH = BASE_DIR / 'scheduler.db'

# 修复：使用绝对路径读取SQL文件
SCHEMA_PATH = Path(__file__).resolve().parent / 'db_schema.sql'

def init_db(db_path='scheduler.db'):
    """初始化数据库（创建表）"""
    if not os.path.exists(db_path):
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        # 创建事件表
        cursor.execute('''
        CREATE TABLE events (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            description TEXT,
            event_time TEXT NOT NULL,
            reminder_time TEXT,
            category TEXT,
            recurring_type TEXT,
            recurring_end_date TEXT
        )
        ''')
        # 创建设置表
        cursor.execute('''
        CREATE TABLE settings (
            key TEXT PRIMARY KEY,
            value TEXT
        )
        ''')
        conn.commit()
        conn.close()

def get_db_connection(db_path='scheduler.db'):
    """获取数据库连接（修复导入错误）"""
    conn = sqlite3.connect(db_path)
    return conn
def get_connection():
    """获取数据库连接（避免重复连接）"""
    return sqlite3.connect(DB_PATH)

def is_db_initialized():
    """检查数据库是否已初始化（通过表是否存在）"""
    try:
        conn = get_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='events'")
        return cursor.fetchone() is not None
    except:
        return False
    finally:
        conn.close()

# 启动时自动初始化（main.py中调用）
if __name__ == "__main__":
    if not is_db_initialized():
        init_db()